<script setup lang="ts">
import { computed, reactive, watch } from 'vue';
import { useFormRules, useNaiveForm } from '@/hooks/common/form';
import { $t } from '@/locales';
import { tagInfoGet, tagInfoSave, tagInfoUpdate } from '@/service/api/tagInfo';

defineOptions({
  name: 'ArticelOperateDrawer'
});

interface Props {
  /** the type of operation */
  operateType: NaiveUI.TableOperateType;
  /** the edit row data */
  rowData?: Api.SystemManage.TagInfo | null;
}

const props = defineProps<Props>();

interface Emits {
  (e: 'submitted'): void;
}

const emit = defineEmits<Emits>();

const visible = defineModel<boolean>('visible', {
  default: false
});

const { formRef, validate, restoreValidation } = useNaiveForm();
const { defaultRequiredRule } = useFormRules();

const title = computed(() => {
  const titles: Record<NaiveUI.TableOperateType, string> = {
    add: '新增标签',
    edit: '编辑标签'
  };
  return titles[props.operateType];
});

type Model = Pick<Api.SystemManage.TagInfo, 'id' | 'name' | 'readNum' | 'sort' | 'followNum'>;

const model: Model = reactive(createDefaultModel());

function createDefaultModel(): Model {
  return {
    id: '',
    name: '',
    readNum: 0,
    sort: 0,
    followNum: 0
  };
}

type RuleKey = Extract<keyof Model, 'name'>;

const rules: Record<RuleKey, App.Global.FormRule> = {
  name: defaultRequiredRule
};

async function getRoleOptions() {}

function handleInitModel() {
  Object.assign(model, createDefaultModel());

  if (props.operateType === 'edit' && props.rowData) {
    Object.assign(model, props.rowData);
    tagInfoGet({ id: props.rowData.id }).then(({ data, error }) => {
      if (!error) {
        Object.assign(model, data);
      }
    });
  }
}

function closeDrawer() {
  visible.value = false;
}

async function handleSubmit() {
  await validate();
  switch (props.operateType) {
    case 'add': {
      const { error } = await tagInfoSave(model);
      if (!error) {
        window.$message?.success($t('common.addSuccess'));
      }
      break;
    }
    case 'edit': {
      const { error } = await tagInfoUpdate(model);
      if (!error) {
        window.$message?.success($t('common.updateSuccess'));
      }
      break;
    }
    default:
      break;
  }

  closeDrawer();
  emit('submitted');
}

watch(visible, () => {
  if (visible.value) {
    handleInitModel();
    restoreValidation();
    getRoleOptions();
  }
});
</script>

<template>
  <NDrawer v-model:show="visible" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="标签名称" path="name">
          <NInput v-model:value="model.name" placeholder="请输入话题名称" />
        </NFormItem>
        <NFormItem label="阅读量" path="readNum">
          <NInputNumber v-model:value="model.readNum" placeholder="阅读量" />
        </NFormItem>
        <NFormItem label="关注数" path="followNum">
          <NInputNumber v-model:value="model.followNum" placeholder="关注数" />
        </NFormItem>
        <NFormItem label="排序" path="sort">
          <NInputNumber v-model:value="model.sort" placeholder="排序" />
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>

<style scoped></style>
